package com.study.shiro.shirosimpledemo;

/**
 * Create by zhaihongwei on 2018/2/9
 * 认证测试
 */

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.junit.Test;

import java.util.Arrays;

public class AuthenticationTest2 {
    //用户登录和退出
    @Test
    public void testLoginAndLoginOut(){

        //创建一个securityManager 通过ini文件创建
        Factory<SecurityManager> securityManagerFactory = new IniSecurityManagerFactory("classpath:shiro-permission.ini");
        //创建SecurityManager
        SecurityManager securityManager = securityManagerFactory.getInstance();
        //将SecurityManager创建到生成环境中
        SecurityUtils.setSecurityManager(securityManager);

        /*-------------------------------------以上步骤类似于读取数据库中的信息，将ini文件作为数据源------------------------------------*/

        //从SecurityUtils 构建一个subject ， 获取用户
        Subject subject = SecurityUtils.getSubject();
        //认证 提交认证token , 这只用户名和密码
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken("zhangsan","zs123");

        try {
            // 登录
            subject.login(usernamePasswordToken);
            System.out.println("用户时候通过认证：" + subject.isAuthenticated());
        }catch(AuthenticationException ex){
            System.out.println("用户名或者密码错误！！");
        }

        // 再权限授权验证(单个)
        Boolean isPermittedOne = subject.isPermitted("user:create");
        System.out.println("单个权限认证："+isPermittedOne);
        // 授权验证权限（多个）
        Boolean isPermittedAll = subject.isPermittedAll("user:create", "user:update");
        System.out.println("多个权限认证：" + isPermittedAll);


        // 另外也可以角色验证权限（不建议）
        Boolean ishasRole=   subject.hasRole("role2");
        Boolean ishasRoleAll=  subject.hasAllRoles(Arrays.asList("role1","role2"));
        System.out.println("单个角色验证："+ishasRole+"|多个角色验证"+ishasRoleAll);
    }
}